<template>
  <q-dialog v-model="visible">
    <q-card style="min-width: 22rem">
      <q-card-section>
        <q-file
          outlined
          v-model="picture"
          label="点击此处以上传地图图片"
          clearable
        >
          <template v-slot:before>
            <div class="text-h6">上传地图图片</div>
          </template>
        </q-file>
      </q-card-section>
      <q-slide-transition>
        <div v-if="iconBase64 !== null">
          <q-separator />
          <q-card-section>
            <q-img :src="iconBase64" />
          </q-card-section>
          <div class="bg-primary">
            <q-btn
              class="full-width text-h6"
              stretch
              color="primary"
              @click="modify"
              label="录入地图图片"
            />
          </div>
        </div>
      </q-slide-transition>
    </q-card>
  </q-dialog>
</template>

<script>
import { ref, watch } from "vue";
import { useAPIStore } from "stores/api";
import { api } from "boot/axios";
import { useQuasar } from "quasar";

export default {
  name: "MapImgUploader",
  props: {
    remote: { type: Boolean, default: false },
  },
  setup(props) {
    const $q = useQuasar();
    const visible = ref(false);
    const picture = ref(null);
    const iconBase64 = ref(null);
    const map = ref({});
    watch(picture, (value) => {
      if (value !== null) {
        const reader = new FileReader();
        reader.readAsDataURL(value);
        reader.onload = () => {
          iconBase64.value = reader.result;
        };
        reader.onerror = function (error) {
          console.log("Error: ", error);
        };
      } else {
        iconBase64.value = null;
      }
    });

    return {
      visible,
      picture,
      iconBase64,
      map,
      show(mapID) {
        api.get(useAPIStore().mapUrl + "map/id/" + mapID).then((rs) => {
          map.value = rs.data;
          visible.value = true;
        });
      },
      modify() {
        if (props.remote) {
          map.value.mapRemote64 = iconBase64.value.slice(22);
        } else {
          map.value.mapBase64 = iconBase64.value.slice(22);
        }
        api.put(useAPIStore().mapUrl + "map", map.value).then((rs) => {
          if (rs.data === "modified") {
            $q.notify({
              message: "地图修改成功",
              type: "positive",
            });
            visible.value = false;
          }
        });
      },
    };
  },
};
</script>
